package com.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution16 {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> tmp = new LinkedList<>();
    boolean[] used;


    public List<List<Integer>> permuteUnique(int[] nums) {
        used = new boolean[nums.length];
        Arrays.fill(used,false);
        Arrays.sort(nums);
        backTracking(nums);
        return res;
    }


    public void backTracking(int[] nums) {
        if (tmp.size() == nums.length) {
            res.add(new ArrayList<>(tmp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue;
            if (i>0&&nums[i-1]==nums[i]&&!used[i-1]) continue;
            tmp.add(nums[i]);
            used[i] = true;
            backTracking(nums);
            used[i] = false;
            tmp.removeLast();
        }

    }
}
